﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace Kokomo.Mirror.PeFormat
{
	[Description("COR 2.0 Metadata Root Header")]
	public class Cor20MetadataRootHeader : PeHeaderStruct
	{
		public static readonly int Magic = 0x424a5342;

		[DisplayName("Signature")]
		[TypeConverter(typeof(HexConverter))]
		public int Signature { get; private set; }

		[NonSerializedProperty]
		[DisplayName("Is signature valid?")]
		public bool IsSignatureValid { get { return this.Signature == Magic; } }

		public Version Version { get; private set; }

		[Browsable(false)]
		public int Reserved { get; private set; }

		[TypeConverter(typeof(HexConverter))]
		public int Length { get; private set; }

		private string _versionString;
		[DisplayName("Version")]
		[SerializedArray(ArrayLengthEncoding.ElementPrefixField, "Length")]
		public string VersionString
		{
			get { return this._versionString; }
			private set
			{
				this._versionString = (value == null) ? null : value.TrimEnd('\0');
			}
		}

		[TypeConverter(typeof(HexConverter))]
		public short Flags { get; private set; }	// Always zero

		public short Streams { get; private set; }

		[SerializedArray(ArrayLengthEncoding.ElementPrefixField, "Streams")]
		[Browsable(false)]
		public Cor20StreamHdr[] StreamHeaders { get; private set; }

		public Cor20StreamHdr GetStreamHeader(string streamName)
		{
			if (streamName == null) throw new ArgumentNullException("streamName");
			if (this.StreamHeaders == null) throw new InvalidOperationException("Header not initialized");

			foreach (var streamHeader in this.StreamHeaders)
			{
				if (streamHeader.Name == streamName) return streamHeader;
			}

			return null;
		}
	}
}
